from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData
from django.conf import settings
from .import constants


# 生成访问令牌
def generate_access_token(openid):
    # 秘钥， 有效期
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.ACCESS_TOKEN_EXPIRES)
    data = {"openid": openid}
    # 加密
    access_token = serializer.dumps(data)
    return access_token.decode("utf-8")


# 校验访问令牌
def check_access_token(access_token_openid):
    # 秘钥
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.ACCESS_TOKEN_EXPIRES)
    try:
        # 解密
        data = serializer.loads(access_token_openid)
    except BadData:
        return None
    else:
        return data.get("openid")
